package com.wstuo.common.config.authorization.service;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import com.wstuo.common.config.authorization.dao.IAuthorizationDAO;
import com.wstuo.common.config.authorization.dto.AuthorizationDTO;
import com.wstuo.common.config.authorization.entity.Authorization;
import com.wstuo.common.dto.BaseDTO;
import com.wstuo.common.dto.PageDTO;

/**
 * 授权管理Service
 * 
 * @author liufei
 * 
 */
public class AuthorizationService implements IAuthorizationService {
	@Autowired
	private IAuthorizationDAO authorizationDAO;

	/**
	 * 保存授权数据
	 * 
	 * @param dto
	 * */
	@Transactional
	public void Save(AuthorizationDTO dto) {
		Authorization entity = new Authorization();
		BaseDTO.dto2entity(dto, entity);
		authorizationDAO.save(entity);
		dto.setAuthId(entity.getAuthId());

	}

	/**
	 * 更新授权数据
	 * 
	 * @param dto
	 * */
	@Transactional
	public void update(AuthorizationDTO dto) {
		Authorization entity = authorizationDAO.findById(dto.getAuthId());
		entity.setAuthName(dto.getAuthName());
		entity.setAuthPawd(dto.getAuthPawd());
		entity.setLastUpdater(dto.getCreator());
		entity.setAuthType(dto.getAuthType());
		authorizationDAO.merge(entity);

	}

	/**
	 * 删除授权数据
	 * 
	 * @param ids
	 * */
	@Transactional
	public void delete(Long[] ids) {
		authorizationDAO.deleteByIds(ids);

	}

	/**
	 * 分页查找数据
	 */
	public PageDTO findPagerAuthorization(AuthorizationDTO authorizationDTO, int start, int limit, String sidx, String sord) {

		PageDTO p = authorizationDAO.findPagerAuthorization(authorizationDTO, start, limit, sidx, sord);
		@SuppressWarnings("unchecked")
		List<Authorization> entities = (List<Authorization>) p.getData();
		List<AuthorizationDTO> dtos = new ArrayList<AuthorizationDTO>(entities.size());

		for (Authorization entity : entities) {
			AuthorizationDTO adto = new AuthorizationDTO();
			AuthorizationDTO.entity2dto(entity, adto);
			dtos.add(adto);
		}

		p.setData(dtos);
		return p;
	}

	/**
	 * 更具类型查找
	 * 
	 * @param type
	 * */
	public Authorization findByAuthType(String type) {

		return authorizationDAO.findUniqueBy("authType", type);

	}

}
